package org.zhq.core;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author zhengquan
 * @date 2019/2/24
 */
public abstract class ScheduleTask implements Runnable {
    protected final long idleTimeoutMilliseconds;
    protected final Connector connector;

    private volatile Scheduler scheduler;

    private ScheduledFuture scheduledFuture;

    protected ScheduleTask(long idleTimeout, TimeUnit unit, Connector connector) {
        this.idleTimeoutMilliseconds = unit.toMillis(idleTimeout);
        this.connector = connector;
    }

    synchronized void schedule(Scheduler scheduler) {
        this.scheduler = scheduler;
        schedule(idleTimeoutMilliseconds);
    }


    synchronized void unSchedule() {
        if (scheduler != null) {
            scheduler = null;
        }
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            scheduledFuture = null;
        }
    }

    protected synchronized void schedule(long timeoutMilliseconds) {
        if (scheduler != null) {
            scheduledFuture = scheduler.schedule(this, timeoutMilliseconds, TimeUnit.MILLISECONDS);
        }
    }

    @Override
    public void run() {

    }
}
